package com.m3958.firstgwt.client;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.core.client.JsArray;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.History;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.m3958.firstgwt.client.datasource.MenuItemDataSource;
import com.m3958.firstgwt.client.datasource.MenuLevelDataSource;
import com.m3958.firstgwt.client.datasource.RoleDataSource;
import com.m3958.firstgwt.client.datasource.SiteConfigDataSource;
import com.m3958.firstgwt.client.datasource.UserDataSource;
import com.m3958.firstgwt.client.types.ConfigKey;
import com.m3958.firstgwt.client.types.MenuItemCategory;
import com.m3958.firstgwt.client.utils.StringUtils;
import com.m3958.firstgwt.shared.type.SmartConstants;
import com.m3958.gwtutil.clientside.client.AjaxResult;
import com.m3958.gwtutil.clientside.client.IwantAjaxQueenResult;
import com.m3958.gwtutil.clientside.client.LoginOutService;
import com.m3958.gwtutil.clientside.client.SmartFetchPara;
import com.m3958.gwtutil.clientside.client.YuiWrapper;
import com.m3958.gwtutil.clientside.client.constants.SmartOperationName;
import com.m3958.gwtutil.clientside.client.constants.SmartSubOperationName;
import com.m3958.gwtutil.clientside.client.jso.MenuitemJso;
import com.m3958.gwtutil.clientside.client.jso.SiteConfigJso;
import com.m3958.gwtutil.clientside.client.jso.SmartResponseJsoWrap;
import com.m3958.gwtutil.clientside.client.jso.SmartSuccessResponseJso;
import com.m3958.gwtutil.clientside.client.jso.WebSiteJso;
import com.m3958.gwtutil.clientside.client.utils.HttpAjaxQueen;
import com.smartgwt.client.util.SC;

//這裡不要注入viewService，不然這個狀態就無法在View裡面使用，會引起循環注入。

@Singleton
public class AppStatus implements IwantAjaxQueenResult{
	
	private String initToken;
	
	@Inject
	private LoginOutService lios;
	
	private boolean appLoaded;

	private boolean confirmInProgress;
	
	private WebSiteJso webSite;
	
	@Inject
	private HttpAjaxQueen ajaxQueen;
	
	@Inject
	private YuiWrapper yui;
	
	public int menuLevelId = SmartConstants.NONE_EXIST_MODEL_ID;
	
	private JsArray<MenuitemJso> menuitems;
	
	
	public JsArray<MenuitemJso> getMenuitems() {
		return menuitems;
	}

	private JsArray<SiteConfigJso> clientConfigs;
	
	private String[] editableExts;
	
	//已经登录
	public void start(String siteId){
		SC.showPrompt("程序初始化中......请稍候");
		SmartFetchPara sfp = new SmartFetchPara();
		sfp.putModelName(MenuItemDataSource.className);
		sfp.putOpType(SmartOperationName.FETCH.toString());
		sfp.putSubOpType(SmartSubOperationName.MANY_TO_MANY.toString());
		sfp.put("_isMaster",false);
		sfp.putRelationModelName(MenuLevelDataSource.className);
		sfp.putRelationModelId(lios.getLoginedUser().getMenuLevelId() + "");
		sfp.putUrl("/smartcfud");
		sfp.putRelationPropertName("menuitems");
		ajaxQueen.addItem(sfp, "menuitems");
		
		SmartFetchPara sfp1 = new SmartFetchPara();
		sfp1.putModelName(RoleDataSource.className);
		sfp1.putOpType(SmartOperationName.FETCH.toString());
		sfp1.putSubOpType(SmartSubOperationName.MANY_TO_MANY.toString());
		sfp1.put("_isMaster",false);
		sfp1.putRelationModelName(UserDataSource.className);
		sfp1.putRelationModelId(lios.getLoginedUser().getId() + "");
		sfp1.putUrl("/smartcfud");
		sfp1.putRelationPropertName("roles");
		ajaxQueen.addItem(sfp1, "roles");
		
		SmartFetchPara sfp2 = new SmartFetchPara();
		sfp2.putModelName(SiteConfigDataSource.className);
		sfp2.putOpType(SmartOperationName.FETCH.toString());
		sfp2.put("clientSide", true);
		sfp2.putUrl("/smartcfud");
		ajaxQueen.addItem(sfp2, "siteconfig");
		
		ajaxQueen.start(AppStatus.this);
	}
	
	
	public boolean allowEdit(String fn){
		String ext = StringUtils.getFileExtensionWithDot(fn);
		if(clientConfigs == null)return false;
		if(editableExts == null){
			for(int i=0;i<clientConfigs.length();i++){
				SiteConfigJso scf = clientConfigs.get(i); 
				String ck = scf.getConfigKey();
				if(ck.equals((ConfigKey.ALLOW_EDIT_EXTS.getEname()))){
					String value = clientConfigs.get(i).getConfigValue();
					editableExts = value.split("\\s");
				}
			}
			if(editableExts == null){
				editableExts = new String[]{};
			}
		}
		for(String ex:editableExts){
			if(ex.equalsIgnoreCase(ext)){
				return true;
			}
		}
		return false;
	}

	public void init(JSONObject jo){
		editableExts = null;
//		superman = appvars.get(GlobalConstants.AppVarFields.IS_SUPERMAN).isBoolean().booleanValue();
//		JSONObject userJson = appvars.get(GlobalConstants.AppVarFields.LOGIN_USER).isObject();
//		su = (UserJso) userJson.isObject().getJavaScriptObject();
//		if(appvars.containsKey(GlobalConstants.AppVarFields.CLIENT_SIDE_CONFIGS))
//			clientConfigs = appvars.get(GlobalConstants.AppVarFields.CLIENT_SIDE_CONFIGS).isArray();
		
//		if(appvars.containsKey(GlobalConstants.AppVarFields.CLIENT_SITE_CONFIGS))
//			setWebSite((WebSiteJso) appvars.get(GlobalConstants.AppVarFields.CLIENT_SITE_CONFIGS).isObject().getJavaScriptObject());
//		JSONValue mo = jo.get(GlobalConstants.AppVarFields.MENU_LEVEL_ID);
		//mo isNull只有在值是jsonnull的情况下才返回有效引用，否则是null。
//		if(mo != null && mo.isNull() == null){
//			menuLevelId = (int) mo.isNumber().doubleValue();
//		}
		//{\"createdAt\":\"2010-10-08T09:36:47\",\"id\":5652,\"menuItemCat\":\"BASE\",\"title\":\"用户管理\",\"uniqueName\":\"BASE_USER_TAB\"}
		//分组可以在客户端写死，根据BASE，OA这样写死，如果有就显示，没有就不显示。
//		JSONArray menuitems = appvars.get(GlobalConstants.AppVarFields.MAIN_MENU_ITEMS).isArray();
		
		//可以是一个hashmap，BASE-》【】，OA-》【】
		
		
//		for(MenuItemCategory mic : MenuItemCategory.values()){
//			menuItemSections.put(mic, new JSONArray());
//		}
		
//		Map<MenuItemCategory, Integer> mi = new HashMap<MenuItemCategory, Integer>();
		
//		for(int i=0;i<menuitems.size();i++){
//			MenuItemCategory mic = MenuItemCategory.valueOf(menuitems.get(i).isObject().get(MenuItemField.MENUITEMCAT.getEname()).isString().stringValue());
//			int t = (mi.get(mic) == null ? 0 : mi.get(mic));
//			menuItemSections.get(mic).set(t, menuitems.get(i));
//			mi.put(mic, ++t);
//		}
	}
	
//	public boolean isSuperman() {
//		return superman;
//	}

//	public void setSu(UserJso loginUser) {
//		su = loginUser;
//	}
//
//	public UserJso getSu() {
//		return su;
//	}


//	public  void setObjectClassNameJsos(JsArray<ObjectClassNameJso> objectClassNameJsos) {
//		this.objectClassNameJsos = objectClassNameJsos;
//	}


//	@SuppressWarnings("unchecked")
//	public JsArray<ObjectClassNameJso> getObjectClassNameJsos() {
//		if(objectClassNameJsos == null){
//			objectClassNameJsos = (JsArray<ObjectClassNameJso>) appvars.get(GlobalConstants.AppVarFields.OBJECT_CLASS_NAMES).isArray().getJavaScriptObject();
//		}
//		return objectClassNameJsos;
//	}
//	

	
	public void setInitToken(String initToken) {
		this.initToken = initToken;
	}
	public String getInitToken() {
		return initToken;
	}

	public void setAppLoaded(boolean appLoaded) {
		this.appLoaded = appLoaded;
	}
	public boolean isAppLoaded() {
		return appLoaded;
	}
	


	public void setConfirmInProgress(boolean confirmInProgress) {
		this.confirmInProgress = confirmInProgress;
	}

	public boolean isConfirmInProgress() {
		return confirmInProgress;
	}


	public void setWebSite(WebSiteJso webSite) {
		yui.logString("appstatus:");
		yui.logJso(webSite);
		this.webSite = webSite;
	}

	public WebSiteJso getWebSite() {
		return webSite;
	}
	
	public String getSiteId(){
		if(webSite != null){
			return getWebSite().getId() + "";
		}else{
			return SmartConstants.NONE_EXIST_MODEL_ID_STR;
		}
		
	}
	

	@Override
	public void onAjaxQueenDataArrival(List<AjaxResult> ars) {
		for(AjaxResult ar : ars){
			SmartResponseJsoWrap rjw = ar.getJsObject().cast();
			SmartSuccessResponseJso rj = rjw.getSmartResponseJso().cast();
			if("menuitems".equals(ar.getDistinct())){
				yui.logJso(rj);
				menuitems = rj.getDataArray().cast();
				yui.logJso(menuitems.cast());
			}else if("siteconfig".equals(ar.getDistinct())){
				clientConfigs = rj.getDataArray().cast();
			}
		}
		
	    if(initToken.length() > 0 && !initToken.contains("/LOGIN/")){
	    	String tk = initToken + ",random=" + new Date().getTime();
	    	History.newItem(tk);
	    }else{
	    	History.newItem(FirstGwt.defaultToken,true);//default
	    }
		SC.clearPrompt();
	}

}
